#include <bits/stdc++.h>
using namespace std;
#define int long long

signed main() {
    int n;
    cin >> n;
    vector<vector<int>> g(n);
    for(int i = 0; i < n - 1; i++) {
        int a, b;
        cin >> a >> b;
        a--, b--;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    vector<int> a(n);
    int sum = 0;
    for(int i = 0; i < n; i++) cin >> a[i], sum += a[i];

    vector<int> ans(n);

    auto dfs = [&](auto&& dfs, int u, int fa, int d) ->void {
        ans[0] += d * a[u];
        for(int x : g[u]) {
            if(x == fa) continue;
            dfs(dfs, x, u, d + 1);
            a[u] += a[x];
        }
    };

    dfs(dfs, 0, -1, 0);

    auto reroot = [&](auto&& reroot, int u, int fa) ->void {
        for(int x : g[u]) {
            if(x == fa) continue;
            ans[x] = ans[u] + sum - 2 * a[x];
            reroot(reroot, x, u);
        }
    };

    reroot(reroot, 0, -1);
    
    cout << *min_element(ans.begin(), ans.end()) << endl;

    return 0;
}